console.log("versions: 2020年12月15日14:44:10");
var myCanvasDraw = null;
var app = new Vue({
    el: '#app',
    data: {
        networkError: false, //网络是否异常
        userInfo: {
            nickName: "", //微信昵称
            avatar: "" //微信头像
        },
        todayInfo: {
            giftStatus: false, //今日是否抽奖
            gatheStatus: false, //抽奖是否提交过信息
            giftId: '', //奖品ID
        },
        winH: window.innerHeight,
        loadingPercent: 0, //加载进度
        page: '', //loading home game save shake awards privancy
        page2: '', //save
        tab: 'tab1', //tab1  tab2_gs tab2_kfc tab2_tree tab2_al 
        element: { //装扮元素
            tab1_01: "images/element/tab1-01.png",
            tab1_02: "images/element/tab1-02.png",
            tab1_03: "images/element/tab1-03.png",
            tab1_04: "images/element/tab1-04.png",
            tab2_zl_01: "images/element/tab2-zl-01.png",
            tab2_zl_02: "images/element/tab2-zl-02.png",
            tab2_zl_03: "images/element/tab2-zl-03.png",
            tab2_zl_04: "images/element/tab2-zl-04.png",
            tab2_kfc_01: "images/element/tab2-kfc-01.png",
            tab2_kfc_02: "images/element/tab2-kfc-02.png",
            tab2_kfc_03: "images/element/tab2-kfc-03.png",
            tab2_kfc_04: "images/element/tab2-kfc-04.png",
            tab2_gs_01: "images/element/tab2-gs-01.png",
            tab2_gs_02: "images/element/tab2-gs-02.png",
            tab2_gs_03: "images/element/tab2-gs-03.png",
            tab2_gs_04: "images/element/tab2-gs-04.png",
        },
        elementNum: 0, // 添加的圣诞元素数量实时统计
        targetElement: "", //选中的目标装扮元素
        myCanvasDraw: null, //目标canvas元素
        targetInput: "", //用户输入的文案
        creating: false, //判断是否正在生成中
        showLotteryBegin: false, //是否显示提示抽奖浮层
        awardsTarget: {
            name: '',
            type: '',
            image: '',
        }, //中奖后的奖品图
        userMutually: { //leads
            name: "",
            mobile: "",
            address: "",
        },
        togglePrivancy: false, //是否勾选隐私政策
        padding: false, //接口是否在padding中
        shared: false, //当前制作流程是否成功调用过分享接口
        currentTree: null, //当前的圣诞树
        isFocus: true, //是否关注公众号
        originCanvasImg: '', //装扮后的原始圣诞树
    },
    mounted: function() {
        var _self = this;
        window.onresize = function() { //注册监听函数
            _self.winH = window.innerHeight;
        };
        this.wxShare(); //配置微信分享
        _self.$nextTick(function() {
            console.log(1);
            _self.getInfoFn();
        })
    },
    watch: {

    },
    computed: {
        bg: function() {
            return (this.page === 'loading') ? 'bg1' : 'bg2';
        },
        ratio: function() {
            winH = this.winH;
            if (winH < 1250) {
                var result = winH / 1250 * .95;
                return `transform:scale(${result})`
            }
            return `transform:scale(1)`
        },
    },
    methods: {
        loading: function(callback) {
            var _self = this;
            var inited = false;
            var saveStatus = [];
            var addStatus = function() {
                saveStatus.push(true);
                var percent = saveStatus.length / loadingAssets.length;
                _self.loadingPercent = Math.floor(percent * 100).toFixed(0);
                if (_self.loadingPercent == 100 && !inited) {
                    inited = true;
                    setTimeout(function() {
                        callback(true)
                    }, 200);
                };
            }
            for (var i = 0, target; target = loadingAssets[i++];) {
                (function() {
                    var img = new Image();
                    img.onload = function() {
                        addStatus();
                    };
                    img.onerror = function() {
                        addStatus();
                    }
                    img.src = target;
                }());
            }
            var checkLoadingStatus = setTimeout(function() {
                clearTimeout(checkLoadingStatus);
                //12s后状态数组仍然不符合总长度，则强制显示
                if (_self.loadingPercent !== 100 && !inited) {
                    inited = true;
                    _self.loadingPercent = 100;
                    callback(true);
                }
            }, 12000);
        },
        getInfoFn: function() {
            var _self = this;
            _self.checkFocus(function() {});
            $.ajax({
                url: "/getUserInfo",
                type: "POST",
                cache: false,
                dataType: "JSON",
                data: {},
                success: function(res) {
                    console.log("接口getInfo返回数据：");
                    console.log(res);
                    if (res.code == 0) {
                        _self.userInfo = res.data.userInfo;
                        _self.todayInfo = res.data.todayInfo;
                        if (_self.todayInfo.giftStatus) {
                            if (!_self.todayInfo.gatheStatus && _self.todayInfo.giftId != 100) { //已抽奖，未领奖 且 不是卡券
                                console.log(awardslist);
                                if ((awardslist[_self.todayInfo.giftId])) { //灾备处理，如果已抽奖，但是没有奖品信息
                                    _self.awardsTarget = awardslist[_self.todayInfo.giftId];

                                    _self.page = 'awards';
                                    return;
                                }

                            }
                        }
                        _self.page = 'loading';
                        _self.loading(function() {
                            _self.page = "home";
                        });
                    } else if (res.code == 1100) {
                        window.location.href = '/wxOauth?redirect_url=' + encodeURIComponent(window.location.href.split('#')[0]);
                    } else {
                        setTimeout(function() {
                            if (res.errMsg) {
                                alert("网络有些问题，建议您刷新重试，错误信息：" + res.errMsg);
                                return;
                            };
                        }, 1000);
                    }
                },
                error: function(res) {
                    _self.networkError = true;
                    _self.page = 'loading';
                    _self.loading(function() {
                        _self.page = "home";
                    });
                    alert("网络有些问题，建议您稍后再试");
                }
            });
        },
        checkFocus: function(callback, bool) {
            console.log("判断用户是否公众号:");
            var _self = this;
            if (_self.padding) return;
            _self.padding = true;
            $.ajax({
                url: "/getSubscribeInfo",
                type: "POST",
                cache: false,
                dataType: "JSON",
                data: {},
                success: function(res) {
                    _self.padding = false;
                    try {
                        console.log("查询是否关注公众号接口返回：");
                        console.log(res.data.wechatInfo.subscribe);
                        if (res.code == 0) {
                            if (res.data.wechatInfo.subscribe == 1) {
                                gaEvent('isfollower');
                                callback(true);
                                _self.isFocus = true;
                                // alert("已关注公众号");
                            } else {
                                gaEvent('notfollower');
                                _self.isFocus = false;
                                callback(false);
                                $(".not_focus").show();
                            }
                        } else {
                            alert("网络有些问题，建议您稍后再试");
                        }
                    } catch (e) {

                    }
                },
                error: function(res) {
                    _self.padding = false;
                    // alert("网络有些问题，建议您稍后再试");
                }
            });
        },
        setTargetElement: function(v) {
            var _self = this;
            if (!v) return;
            _self.targetElement = v || '';
            _self.addEl(_self['element'][v]);
        },
        resetEl: function() {
            this.targetElement = '';
            this.tab = 'tab1';
        },
        beginGame: function() {
            gaEvent('start');
            _self = this;

            if (_self.networkError) {
                alert("网络有些问题，建议您稍后再试");
                return;
            }

            if (!_self.isFocus) {
                _self.checkFocus(function(v) {
                    if (v) {
                        _self.page = 'game';
                        setTimeout(function() {
                            _self.initCanvas();
                        }, 200);
                    }
                });
                // $(".not_focus").show();
                return;
            }
            _self.page = 'game';
            setTimeout(function() {
                _self.initCanvas();
            }, 200);
        },
        initCanvas: function() {
            console.log("initCanvas");
            var width = $(".game_canvas").width(),
                height = $(".game_canvas").height();
            console.log(width, height);
            myCanvasDraw = new canvasDrawImages({
                containerElement: document.querySelector('#game_canvas'),
                width: width,
                height: height,
                minScale: 0.3, //缩放最小倍数
                // ontouchMove: function (hitLayer) {
                //     console.log(hitLayer)
                // }
            });
            //添加事件
            myCanvasDraw.ontouchMove = function(hitLayer) {
                //选中元素对象
                // console.log(hitLayer)
                if (hitLayer.x > (width - 60) && hitLayer.y > (height - 50)) {
                    myCanvasDraw.removeChild(hitLayer);
                    _self.elementNum--;
                }
            }

            myCanvasDraw.ontouchDown = function(hitLayer) {
                // console.log(hitLayer.x)
            }

            _self.addEl(_self.element.tab1_01);

        },
        addEl: function(src) {
            console.log(src);
            var _self = this;

            var img1 = new Image();
            img1.src = src;
            if (src.indexOf("element/tab1") !== -1) {
                img1.width = 538;
                img1.height = 700;
            }
            var imgM;
            img1.onload = function() {
                imgM = new ImgMaterial(img1, myCanvasDraw.width / 2, myCanvasDraw.height / 2);
                //透明度
                //imgM.alpha = 0.2;

                if (src.indexOf("element/tab1") !== -1) {
                    console.log("------------");
                    // console.log(_self.currentTree);
                    myCanvasDraw.removeChild(_self.currentTree);
                }

                myCanvasDraw.addChild(imgM);

                if (src.indexOf("element/tab1") !== -1) {
                    console.log("设置层级");
                    myCanvasDraw.setChildIndex(imgM, 0);

                    _self.currentTree = imgM;

                    console.log("禁止拖动");
                    //禁止拖动
                    imgM.touchDisable = true;
                }

                //顶点测试显示
                // imgM.test = true;
                _self.elementNum++;
            };
        },
        createPicture: function() {
            var _self = this;
            if (_self.creating) return;
            if (!_self.targetInput) {
                _self.targetInput = "圣诞快乐！";
            };
            if (!_self.elementNum) {
                alert("请先装扮圣诞树哦");
                return;
            };

            if (!_self.currentTree) {
                alert("请选择一颗圣诞树哦");
                return;
            }

            gaEvent('dressready');

            // 生成中，暂时阻止页面交互
            _self.creating = true;
            $(".game").addClass("game_not_touch");
            $(".waiting").show();

            _self.page2 = 'save';

            var c = myCanvasDraw.toDataURL("image/png", .7);
            _self.originCanvasImg = c;

            $(".save_content_userimg").attr("src", c);

            var forPostImg = document.getElementById('save_forsubmit');
            html2canvas(forPostImg, {
                scale: 1,
                width: 500,
                height: 750,
                allowTaint: true,
                useCORS: true, //使用跨域(当allowTaint为true时这段代码没什么用)
                backgroundColor: "transparent"
            }).then(function(canvas) {
                console.log(canvas);
                var dataUrl = canvas.toDataURL("image/png");
                _self.postImg(dataUrl);
                // var img = new Image();
                // img.src = dataUrl;
                // img.classList = "ddddd";
                // document.body.append(img);
            });

        },
        postImg: function(cc) {
            var _self = this;
            $.ajax({
                url: "/submitUserInfo",
                type: "POST",
                cache: false,
                dataType: "JSON",
                data: {
                    christmasImg: cc,
                    greeting: _self.targetInput || '圣诞快乐！'
                },
                success: function(res) {
                    console.log(res);
                    if (res.code == 0) {

                        var qrcodeLink = "https://" + location.host + '/share.html?shareid=' + res.data.shareId + '&utm_source=' + 'share';
                        var qrcode = new QRCode(document.querySelector(".save_content_qrcode"), {
                            text: qrcodeLink,
                            width: 60,
                            height: 60,
                            colorDark: "#ac182d",
                            colorLight: "#ffffff",
                            correctLevel: QRCode.CorrectLevel.H
                        });

                        setTimeout(function() {
                            var myImg = document.querySelector(".save_content_img");
                            //Tips: 文件系统模式访问会出错，需使用server模式
                            html2canvas(myImg, {
                                allowTaint: true,
                                useCORS: true, //使用跨域(当allowTaint为true时这段代码没什么用)
                            }).then(function(canvas) {
                                console.log(canvas);
                                var cc = canvas.toDataURL("image/jpeg");
                                $('.save_foruser').attr('src', cc);
                                _self.creating = false;
                                $(".game").removeClass("game_not_touch");
                                _self.page = '';
                                $(".save").addClass("save_normal");
                                $(".waiting").hide();
                            });
                        }, 200);

                        var shareLink = "https://" + location.host + '/share.html?shareid=' + res.data.shareId + '&utm_source=' + 'share';
                        configShare(shareLink);
                        _self.longPress();

                    } else {
                        alert(res.errMsg);
                    }
                },
                error: function(res) {
                    _self.padding = false;
                    alert("网络有些问题，建议您稍后再试");
                }
            });
        },
        longPress: function() {
            console.log("监听长按");
            var _self = this;
            var timeOutEvent;
            var timer = 1500;
            if (!!browser.versions.ios) timer = 1000;
            $(".save_foruser").on({
                touchstart: function(e) {
                    timeOutEvent = setTimeout(function() {
                        gaEvent('longpress');
                        _self.ajaxShare();
                    }, timer);
                },
                touchmove: function() {
                    clearTimeout(timeOutEvent);
                },
                touchend: function() {
                    clearTimeout(timeOutEvent);
                }
            });
        },
        ajaxShare: function() {

            console.log("调用share");

            var _self = this;

            // 今日已抽奖 或者已有卡券
            if (_self.todayInfo.giftStatus || _self.todayInfo.giftId) return;

            if (_self.showLotteryBegin) return; //如果有"开始抽奖"浮层，阻止继续执行

            if (_self.shared) {
                _self.showLotteryBegin = true;
                return;
            };
            if (_self.padding) return;
            _self.padding = true;
            $.ajax({
                url: "/share",
                type: "POST",
                cache: false,
                dataType: "JSON",
                data: {},
                success: function(res) {
                    _self.padding = false;
                    console.log(res);
                    if (res.code == 0) {
                        _self.shared = true;
                        _self.page2 = '';
                        _self.page = 'shake';
                    } else {
                        _self.showLotteryBegin = false;
                    }
                },
                error: function(res) {
                    _self.showLotteryBegin = false;
                    _self.padding = false;
                    alert("网络有些问题，建议您稍后再试");
                }
            });
        },
        startLottery: function() {

            var _self = this;
            if (_self.padding) return;
            _self.padding = true;
            gaEvent('lottery');
            $.ajax({
                url: "/gift",
                type: "POST",
                cache: false,
                dataType: "JSON",
                data: {},
                success: function(res) {
                    _self.padding = false;
                    console.log("接口gift返回数据：");
                    console.log(res);
                    if (res.code == 0) {
                        _self.awardsTarget = awardslist[res.data];
                        _self.page = 'awards';
                    } else if (res.code == 1606) {
                        _self.padding = false;
                        alert("您已抽奖");
                    } else {
                        alert(res.errMsg);
                    }
                },
                error: function(res) {
                    _self.padding = false;
                    alert("网络有些问题，建议您稍后再试");
                }
            });
        },
        submitLeads: function() {
            var _self = this;
            if (_self.padding)
                return;
            if (_self.todayInfo.gatheStatus) {
                alert("你已提交，请勿重复提交");
                return;
            }
            if (!_self.togglePrivancy) {
                alert("请先勾选隐私协议");
                return;
            };
            if ((_self.userMutually.name).trim() == '') {
                alert("请正确输入姓名");
                return;
            };
            var reg2 = /^1[3|4|5|6|7|8|9][0-9]{9}$/,
                checkPhone = reg2.test(_self.userMutually.mobile);
            if (!checkPhone) {
                alert("请正确输入手机号");
                return;
            }

            if ((_self.userMutually.address).trim() == '') {
                alert("请正确输入地址");
                return;
            };

            gaEvent('submitleads');

            var postData = {
                name: _self.userMutually.name,
                mobile: _self.userMutually.mobile,
                address: _self.userMutually.address
            };

            _self.padding = true;
            $.ajax({
                url: "/saveAddress",
                type: "POST",
                cache: false,
                dataType: "JSON",
                data: postData,
                success: function(res) {
                    _self.padding = false;
                    console.log("接口saveAddress返回数据：");
                    console.log(res);
                    if (res.code == 0) {
                        alert("提交成功");
                    } else {
                        alert(res.errMsg || '提交失败，请稍候再试');
                    }
                },
                error: function(res) {
                    alert("网络有些问题，建议您稍后再试");
                    _self.padding = false;
                }
            });
        },
        wxShare: function() {
            var _self = this;
            $.ajax({
                url: "/jssdkSignature",
                type: "POST",
                cache: false,
                dataType: "JSON",
                data: {
                    "url": encodeURIComponent(window.location.href.split('#')[0])
                },
                success: function(res) {
                    console.log("接口jssdkSignature返回数据：");
                    console.log(res);
                    if (res.code == 0) {
                        var data = res.data;
                        data.jsApiList = ["onMenuShareAppMessage", "onMenuShareTimeline"];
                        data.appId = 'wx5f207b761c92e9c6';
                        wx.config(data);
                    }
                },
                error: function(res) {}
            });
        }
    }
});

$(function() {
    $(".close_focus").on("click", function() {
        $(".not_focus").hide();
    });
})